$(document).ready(function() {
    refreshFiles();
    $('.refreshFiles').click(refreshFiles);
});
intervals = []
timeouts = []
files = []
recipe_queue = {}
refreshFiles = function() { el = document.getElementById('shared-files'); el.src = el.src; }                             
stomp_msg_callback = function(msg) {
      refresh_peer_info(msg);
      refresh_files_info(msg);
      refresh_table('rq_table', msg.recipe_queue);    
      if(msg.recipe_download_queue.length != 0) {
        console.log('download_queue is set');
        console.log(msg.recipe_download_queue);
      }
      refresh_table('rdq_table', msg.recipe_download_queue);
      if(msg.file_queue.length != 0) {
        console.log('file_queue is set');
        console.log(msg.file_queue);
      }
      refresh_table('fcq_table', msg.file_queue); 
      refresh_table('recipes_table', msg.local_recipes);      
      if(msg.search_results != undefined)
          refresh_search_results(msg.search_results); 
      if(msg.sql_results != undefined) {
          console.log("sql_results arrived");    
          create_table('sql-results', msg.sql_results)
      }
}
refresh_peer_info = function(msg) {
  el = $('head title')
  if(el.text() != 'Peer ' + msg.name)
    el.text('Peer ' + msg.name)
  arr = ['id', 'name', 'rpc_host', 'rpc_port', 'external_ip', 'external_port', 
             'tracker_host', 'tracker_port', 'recipe_server_host', 
             'recipe_server_port','recipe_server_status' , 'sent_all_blocks',
             'tracker_status', 'sent_all_recipes' ,'tracker_added_self', 'num_unsent_blocks']
  $(arr).each(function(i,mem) { el = $('#peer-' + mem); if(el.text() != ''+msg[mem]) el.text(msg[mem]) } );   
  if(last_msg == null) {
    $(arr).each(function(i,mem) { $('[name='+mem+']').val(msg[mem]); });
  }
}
refresh_search_results = function(arr) {
  $('[name=file_id]').html('');
  $(arr).each(function(ind, rcp) {
                $('[name=file_id]').append('<option value=' + rcp[0] + ' > ' + 
                                            rcp[1] + '(' + (rcp[2]/1000) + ' KB)' + '</option>');
              
              })
}
refresh_files_info = function(msg) {
  if(files.length != msg.files.length) {
    $('[name=fileind]').html('');
    files = msg.files;
    $(files).each(function(ind, file) {
      $('[name=fileind]').append('<option value=' + ind + '>' + file + '</option>')
    });
  }   
}

var fileinputchanged = function(val) {
   document.getElementById('filename').value = val.split(' ')[0];
}